// map.js
import qqMap from '../../../utils/qqmap'

Page({
  data: {
    // 地图中心点的经纬度
    latitude: 31.040674,
    longitude: 121.618713,
    markers: [
      {
        id: 1,
        latitude: 31.040674,
        longitude: 121.618713,
        width: 24,
        height: 30,
      },
      {
        id: 2,
        latitude: 31.245473,
        longitude: 121.506432,
        // iconPath: '/static/images/marker.png',
        width: 24,
        height: 30,
      },
    ],
    dialogVisible: false,
  },
  onLoad({ id }) {
    this.getRepairDetail(id)
  },
  // 1. 获取维修详情
  async getRepairDetail(id) {
    if (!id) return
    const { code, data: repairDetail } = await wx.http.get(`/repair/${id}`)
    if (code !== 10000) return wx.utils.toast('获取维修详情失败')
    this.setData({
      ...repairDetail,
    })

    // 判断: 只有状态码为2时才进行路径规划
    if (this.data.status === 2) {
      this.getPolyline()
    }
  },

  // 2. 规划路线
  getPolyline() {
    const { markers } = this.data
    qqMap.direction({
      mode: 'driving',
      from: [markers[0].latitude, markers[0].longitude].join(','), // '31.040674, 121.618713'
      to: [markers[1].latitude, markers[1].longitude].join(','), // '31.245473, 121.506432'
      success: (res) => {
        console.log(res)
        var coors = res.result.routes[0].polyline,
          pl = []
        //坐标解压（返回的点串坐标，通过前向差分进行压缩）
        var kr = 1000000
        for (var i = 2; i < coors.length; i++) {
          coors[i] = Number(coors[i - 2]) + Number(coors[i]) / kr
        }
        //将解压后的坐标放入点串数组pl中
        for (var i = 0; i < coors.length; i += 2) {
          pl.push({ latitude: coors[i], longitude: coors[i + 1] })
        }
        // console.log(pl)
        // console.log(pl[Math.floor(pl.length / 2)])

        // 额外加一个点
        markers.push({
          id: 3,
          latitude: pl[Math.floor(pl.length / 2)].latitude,
          longitude: pl[Math.floor(pl.length / 2)].longitude,
          iconPath: '/static/images/marker.png',
          width: 40,
          height: 40,
        })

        this.setData({
          markers,
          polyline: [
            {
              points: pl,
              color: '#FF0000DD',
              width: 4,
            },
          ],
        })
      },
    })
  },

  // 3. 展示取消报修确认对话框
  showDialog() {
    this.setData({
      dialogVisible: true,
    })
  },

  // 4. 点击确认框的取消和确认
  dialogClose(ev) {
    ev.detail === 'confirm' && this.cancelRepair()
  },

  async cancelRepair() {
    const { code } = await wx.http.put(`/cancel/repaire/${this.data.id}`)
    if (code !== 10000) return wx.utils.toast('取消报修失败')
    wx.navigateBack()
  },

  // 5. 修改信息
  gotoRepairForm() {
    wx.navigateTo({
      url: `/repair_pkg/pages/form/index?id=${this.data.id}`,
    })
  },
})
